using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;

using Modbus.Data;
using Modbus.Device;
using Modbus.Utility;
using System.Threading;

namespace YangtzeFilterTestSystem
{
    public partial class PLCTestForm : Form
    {

        private static SerialPort port;

        // create modbus master
        private static IModbusSerialMaster master;

        public PLCTestForm()
        {
            InitializeComponent();

            port = new SerialPort();
            port.PortName = "COM7";
            port.BaudRate = 9600;
            port.Parity = Parity.Even;
            port.DataBits = 8;
            port.StopBits = StopBits.One;
            port.WriteTimeout = 3000;
            port.ReadTimeout = 3000;

            port.Open();

            master = ModbusSerialMaster.CreateRtu(port);

            ValveCBox.SelectedIndex = 0;

            ValueTBox.Text = "0";
        }

        private void OpenValveBtn_Click(object sender, EventArgs e)
        {
            ;
            PLC.Open(Convert.ToUInt16(ValveCBox.SelectedIndex));
        }

        private void CloseValveBtn_Click(object sender, EventArgs e)
        {
            PLC.Close(Convert.ToUInt16(ValveCBox.SelectedIndex));
        }

        private void CloseBtn_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void TestBtn_Click(object sender, EventArgs e)
        {
            try
            {
                master.WriteSingleRegister(0x01, 0, Convert.ToUInt16(ValueTBox.Text));
            }
            catch
            {
                MessageBox.Show("Error in TestBtn_Click");
            }
        }

        private void CoilWriteBtn_Click(object sender, EventArgs e)
        {

            bool Q00Status = true;

            if (Convert.ToInt32(CoilTBox.Text) == 0)
            {
                Q00Status = false;           
            }

            if (Convert.ToInt32(CoilTBox.Text) == 1)
            {
                Q00Status = true;
            }

            try
            {
                master.WriteSingleCoil(0x01, 0, Q00Status);
            }
            catch
            {
                MessageBox.Show("Error in CoilWrite_Click...");
            }

        }




    }
}